package com.bicon.botu.mall.goods.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.core.base.common.BusinessException;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.mall.goods.commons.GoodsConstants;
import com.bicon.botu.mall.goods.dto.OrderVerifyDto;
import com.bicon.botu.mall.goods.dto.ProductSalesVolumeDTO;
import com.bicon.botu.mall.goods.vo.ProductRepertoryInfo;
import com.bicon.botu.mall.goods.entity.ProductRepertory;
import com.bicon.botu.mall.goods.mapper.ProductRepertoryMapper;
import com.bicon.botu.mall.goods.service.IProductRepertoryService;
import com.bicon.botu.mall.goods.vo.ProductSkuVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 产品库存 服务实现类
 * </p>
 *
 * @author 孙永刚
 * @since 2017-07-20
 */
@Service
@Transactional
public class ProductRepertoryServiceImpl extends ServiceImpl<ProductRepertoryMapper, ProductRepertory> implements IProductRepertoryService {

    @Autowired
    private ProductRepertoryMapper mapper;

    @Override
    public Page<ProductRepertoryInfo> getPage(Page<ProductRepertoryInfo> infoPage, Map<String, String> map) {
        List<ProductRepertoryInfo> list = mapper.getProductInfo(infoPage, map);
        List<ProductRepertoryInfo> newList = new ArrayList<>();
        if (list.size() > 0) {
            for (ProductRepertoryInfo info : list) {
                //如果库存余量小于等于警告数量
                if (info.getSurplusNum() <= info.getNoticeNum()) {
                    //库存不足
                    info.setRepertoryState(GoodsConstants.REPERTORY_STATE2);
                } else {
                    info.setRepertoryState(GoodsConstants.REPERTORY_STATE1);
                }
                newList.add(info);
            }
        }
        infoPage.setRecords(newList);
        return infoPage;
    }

    @Override
    public List<ProductSkuVo> getProductSku(String productId) {
        return mapper.getProductSku(productId);
    }

    @Override
    public List<ProductSkuVo> getProductRepertorySku(String productId) {
       List<ProductSkuVo> list= this.getProductSku(productId);
        if (list.size() > 0) {
            for (ProductSkuVo vo:list){
                String[] name = vo.getSkuName().split(",");
                int i=0;
                for (String s:name){
                    Map<Object,String> map = new HashMap<>();

                    String[] sku = s.split(":");
                    if(i==0){
                        map.put("attr1",sku[0]);
                        map.put("attr2",sku[1]);
                        vo.setSkuName1(map);
                    }else {
                        map.put("attr3",sku[0]);
                        map.put("attr4",sku[1]);
                        vo.setSkuName2(map);
                    }
                    i++;
                }

            }

            return list;
        }
        return new ArrayList<>();
    }

    @Override
    public Map<String, Object> repertoryTotal() {
        Map<String,Object> map = new HashMap<>();
        List<ProductSalesVolumeDTO> repertoryWarmTotal = new ArrayList<>();
        repertoryWarmTotal = mapper.repertoryWarmTotal();
        Integer stockout = new ProductRepertory().selectCount(new EntityWrapper().eq("product_num", 0).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        //商品库存警告
        map.put("repertoryWarmTotal",repertoryWarmTotal.size());
        //商品缺货
        map.put("stockout",stockout);
        return map;
    }
    /**
     * 修改库存数量
     *
     * @param type 添加还是减少。1代表添加，2代表减少
     * @param num  操作数量
     * @param repertoryId   库存Id
     * @return
     */
    @Override
    public boolean updateNumberById(int type, int num, String repertoryId) {
        ProductRepertory productRepertory = new ProductRepertory().selectOne(new EntityWrapper<ProductRepertory>().eq("id", repertoryId));
        if (productRepertory != null) {
            if (type == GoodsConstants.NUMBER_1) {
                productRepertory.setProductNum(productRepertory.getProductNum() + num);
            } else if (type == GoodsConstants.NUMBER_2){
                productRepertory.setProductNum(productRepertory.getProductNum() - num);
            }
            productRepertory.preUpdate();
            return productRepertory.updateById();
        }
        return false;
    }

    /**
     * 更新数量
     *
     * @param paramList 更新数量
     * @return
     */
    @Override
    public boolean updateNumber(List<OrderVerifyDto> paramList) {
        if (CollectionUtils.isEmpty(paramList)) {
            throw new BusinessException("商品库存信息为空");
        }
        //获取多个库存id
        Map<String, Integer> verifyDtoMap = new HashMap<>();
        for (OrderVerifyDto verifyDto : paramList) {
            verifyDtoMap.put(verifyDto.getGoodsId(), verifyDto.getGoodsNumber());
        }
        List<ProductRepertory> repertoryList = getList(paramList);
        for (ProductRepertory repertory : repertoryList) {
            repertory.setProductNum(repertory.getProductNum() + verifyDtoMap.get(repertory.getId()));
        }
        return this.updateBatchById(repertoryList);
    }

    /**
     * 添加销量
     *
     * @param paramList   参数列表
     * @return
     */
    @Override
    public boolean addSalesByList(List<OrderVerifyDto> paramList) {
        List<ProductRepertory> repertoryList = getList(paramList);
        //获取多个库存id
        Map<String, Integer> verifyDtoMap = new HashMap<>();
        for (OrderVerifyDto verifyDto : paramList) {
            verifyDtoMap.put(verifyDto.getGoodsId(), verifyDto.getGoodsNumber());
        }
        for (ProductRepertory repertory : repertoryList) {
            repertory.setSales(repertory.getSales() + verifyDtoMap.get(repertory.getId()));
        }
        return this.updateBatchById(repertoryList);
    }

    private List<ProductRepertory> getList(List<OrderVerifyDto> paramList) {
        String[] skuIds = paramList.stream().map(OrderVerifyDto::getGoodsId).toArray(String[]::new);
        List<String> list = Arrays.asList(skuIds);
        List<ProductRepertory> repertoryList = this.selectList(new EntityWrapper<ProductRepertory>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).in("id", list));
        return repertoryList;
    }


    /**
     * 添加销量Id
     *
     * @param num  添加数量
     * @param repertoryId 库存Id
     * @return
     */
    @Override
    public boolean addSalesById(int num, String repertoryId) {
        ProductRepertory productRepertory = new ProductRepertory().selectOne(new EntityWrapper<ProductRepertory>().eq("id", repertoryId));
        if (productRepertory != null) {
            productRepertory.setSales(productRepertory.getSales() + num);
            productRepertory.preUpdate();
            return productRepertory.updateById();
        }
        return false;
    }



    /**
     * 商品销量top10
     *
     * @return
     */
    @Override
    public List<ProductSalesVolumeDTO> salesVolumeTop10(Integer type,String startTime, String endTime) {
        if(type==1){
            return mapper.salesVolumeTop10();
        }else{
            return mapper.salesVolumeTop10ByTime(startTime,endTime);
        }
    }
}
